package com.ljh.mall.mallsearch.thread;

import java.util.concurrent.*;

/**
 * @author ：刘剑鸿
 * @date ：Created in 2023/3/19 21:28
 * @description：
 * @modified By：
 * @version: $
 */
public class CompletableFutureDemo {
    private static ThreadPoolExecutor executor = new ThreadPoolExecutor(5,
            50,
            10,
            TimeUnit.SECONDS,
            new LinkedBlockingDeque<>(100),
            Executors.defaultThreadFactory(),
            new ThreadPoolExecutor.AbortPolicy());

    /**
     * runAsync 没有返回结果
     * @param args
     */
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        CompletableFuture<Void> voidCompletableFuture = CompletableFuture.runAsync(()->{
            System.out.println("线程开始了..." + Thread.currentThread().getName());
            int i = 100/50;
            System.out.println("线程结束了...");
        },executor);

        CompletableFuture<Integer> future = CompletableFuture.supplyAsync(()->{
            System.out.println("线程开始了..." + Thread.currentThread().getName());
            int i = 100 / 0;
            System.out.println("线程结束了...");
            return i;
        },executor).whenCompleteAsync((res,exec)->{
            System.out.println("res = " + res); // 获取返回值
            System.out.println("exec = " + exec);// 获取异常信息
        }).exceptionally((res)->{ // 在异步任务显示的抛出了异常后才会触发的方法
            System.out.println("exceptionally_res = " + res);
            return 10;
        });
        System.out.println("获取的线程的返回结果是：" + future.get() );
    }
}
